<template>
    <NForm ref="formRef" :model="form" inline size="small" :show-label="false" class="mt-4">
        <NGrid x-gap="12" responsive="screen" item-responsive>
            <NFormItemGi span="24 s:12 m:6" prop="mobileNumber">
                <NInput v-model:value="form.mobileNumber" clearable placeholder="手机号/邮箱"></NInput>
            </NFormItemGi>
            <NFormItemGi span="24 s:12 m:6">
                <NButton type="primary" @click="search">
                    <template #icon>
                        <NIcon>
                            <Search />
                        </NIcon>
                    </template>
                    查询
                </NButton>
                <NButton @click="reset" class="ml-2">重置</NButton>
            </NFormItemGi>
        </NGrid>
    </NForm>
    <NDivider style="margin-top: 0px" />
    <NDataTable class="mt-4" :columns="columns" :data="list" :loading="loading"></NDataTable>

    <NFlex justify="flex-end" class="mt-4">
        <NPagination
            v-model:page="pager.pageIndex"
            v-model:page-size="pager.pageSize"
            :item-count="total"
            show-size-picker
            :page-sizes="[10, 20, 50, 100]"
        />
    </NFlex>
</template>

<script setup lang="ts">
import { reactive, ref, watch } from 'vue'
import dayjs from 'dayjs'
import { Search } from '@vicons/carbon'
import { NDivider, NFlex, NButton, type DataTableColumns, type FormInst } from 'naive-ui'
import { querySMSList } from '@/api/user'

defineOptions({
    name: 'SMSList'
})

const formRef = ref<FormInst | null>(null)
const form = ref<Api.User.SMSSearchParams>({
    mobileNumber: null
})

const columns: DataTableColumns<Api.User.SMS> = [
    {
        title: '手机号/邮箱',
        key: 'mobileNumber'
    },

    {
        title: '平台',
        key: 'platform'
    },
    {
        title: '短信',
        key: 'sms'
    },

    {
        title: 'IP',
        key: 'ip'
    },

    {
        title: '创建日期',
        key: 'createdAt',
        render(row) {
            return dayjs(row.createdAt * 1000).format('YYYY-MM-DD HH:mm:ss')
        }
    }
]

const list = ref<Api.User.SMSList>([])
const total = ref(0)
const loading = ref(false)
const pager = reactive({
    pageIndex: 1,
    pageSize: 10
})
const queryData = async () => {
    const { ...opts } = form.value
    loading.value = true
    const [err, res] = await querySMSList({
        ...opts,
        ...pager
    })
    loading.value = false
    if (!err) {
        const { count, list: dataList } = res
        list.value = dataList
        total.value = count
    }
}
queryData()
watch(pager, queryData)

const search = () => {
    pager.pageIndex = 1
    queryData()
}

const reset = () => {
    form.value = {
        mobileNumber: null
    }
    pager.pageIndex = 1
    queryData()
}
</script>
